<?php
ini_set('date.timezone','Asia/Shanghai');
upload();

function upload() {
    $picture = $_POST['picture'];
   // $picture = base64_encode(file_get_contents('http://static.im20.com.cn/msg.crayola.cn/uploads/Home/drawings/2014/12/10/19/304845828_low.jpg'));

    if (!$picture) {
        $ret = array ('status' => 0, 'message' => '参数错误');
        print json_encode($ret);
        exit();
    }
    
    $file = saveBase64BinImg('picture', $picture);

    $ret = array ('status' => 1, 'message' => '上传成功', 'picture' => $file);
    print json_encode($ret);
    exit();
}

function saveBase64BinImg($type, $base64Bin, $ext='jpg') {
    $fileName = substr(md5(time() . rand(0, 9999)), 2, 10) . '.' . $ext;
	$fullFileName = 'upload/images/'  . getTimeHash() . '/' . $fileName; 
	if (!file_exists($fullFileName)) {
		buildDir(dirname($fullFileName));
        if(strpos($base64Bin,',')!==false) $base64Bin = explode(',',$base64Bin)[1];
		@file_put_contents( $fullFileName, base64_decode( $base64Bin ) );
	}
	return 'http://' . $_SERVER['HTTP_HOST'] . '/watson/' . $fullFileName;
}

function buildDir($filepath) {
	$pathArray = explode('/', $filepath);
	$nowPath   = '';
	foreach($pathArray as $key => $value) {
		if ('' == $value) {
			unset($pathArray[$key]);
		}
		else {
			if ($key == 0)
				$nowPath .= $value;
			else
				$nowPath .= '/' . $value;
			if (!is_dir($nowPath)) {
				if (!mkdir($nowPath, 0777)) return false;
			}
		}
	}
	return true;
}

function getTimeHash(){
	$path = date('Y_m_d');
	return $path;
}
?>